package com.csgc.camera.biz.vip

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alipay.sdk.app.PayTask
import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.bean.UserInfo
import com.csgc.camera.bean.UserInfoParams
import com.csgc.camera.biz.other.LoginActivity
import com.csgc.camera.biz.other.activity.WebViewActivity
import com.csgc.camera.constants.Constants
import com.csgc.camera.events.LoginEvents
import com.csgc.camera.http.doSuccess
import com.csgc.camera.http.viewmodel.AppViewModel
import com.csgc.camera.storage.UserPreference
import com.csgc.camera.util.PrivacyProtocolHelper
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.widget.dialog.BuyVipDialog
import com.csgc.camera.widget.dialog.ContactUsDialog
import com.csgc.camera.widget.dialog.LoadingPop
import com.csgc.camera.widget.dialog.OpenVipSuccessDialog
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityVipCenterBinding
import com.drake.channel.receiveEvent
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hlyj.http.base.tool.lib_hlyj_base.bean.BaseResult
import com.hlyj.http.base.tool.lib_hlyj_base.camera.LoginResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.OrderBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.ShopInfoBean
import com.hlyj.http.base.tool.lib_hlyj_base.camera.UserInfoResultBean
import com.hlyj.http.base.tool.lib_hlyj_base.net.ApiCallback
import com.hlyj.http.base.tool.lib_hlyj_base.utils.MMKVUtils
import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.hnyyac.ad.mds.utils.BaseAdSpUtils
import com.ok.common.api.GlobalApi
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class VipCenterActivity :
    BaseBindingActivity<ActivityVipCenterBinding>(ActivityVipCenterBinding::inflate) {
    var quanyiadapter: VipQuanYiAdapter? = null

    companion object {
        fun launch(context: Context) {
            context.startActivity(Intent(context, VipCenterActivity::class.java))
        }
    }

    private val viewModel: AppViewModel by viewModels()
    private val adapter: VipTypeAdapter by lazy {
        val dialog = VipTypeAdapter(this)
        dialog.listener = object : VipTypeAdapter.OnVipTypeClickListener {
            override fun onItemClick(price: Double) {
                binding.tvBuyVip.text = "(¥${price})" + "解锁会员"
               // 滑动到指定位置，确保不超出数据范围
                val targetPosition = minOf(adapter.buyPosition + 1, adapter.list.size - 1)
                binding.rvVipTypeList.smoothScrollToPosition(targetPosition)
            }
        }
        dialog
    }
    private var userInfo: UserInfoResultBean? = null
    private var logInUserInfo: LoginResultBean? = null
    private val userAdapter: JsonAdapter<UserInfo> by lazy {
        val moshi = Moshi.Builder().build()
        val jsonAdapter = moshi.adapter(UserInfo::class.java)
        jsonAdapter
    }

    //特惠购买dialog
    private val specialPriceBuyDialog: BuyVipDialog by lazy {
        val dialog = BuyVipDialog(this)
        dialog.listener = object : BuyVipDialog.OnItemListener {
            override fun onGiveUp() {
                finish()
            }

            override fun onBuyVip(type: Int) {
                payType = type
                if (payType == 0) {
                    binding.ivWxChecked.visibility = View.VISIBLE
                    binding.ivAliChecked.visibility = View.INVISIBLE
                } else {
                    binding.ivWxChecked.visibility = View.INVISIBLE
                    binding.ivAliChecked.visibility = View.VISIBLE
                }


                isBuying = true
                val data = adapter.list[adapter.foreverPosition]
                //buyVip(data.productId, special = 1)


            }
        }
        dialog
    }
    private val loadingPop: LoadingPop by lazy {
        LoadingPop(this, false)
    }
    private val openVipSuccessDialog: OpenVipSuccessDialog by lazy {
        val dialog = OpenVipSuccessDialog(this)
        openVipSuccessDialog.listener = object : OpenVipSuccessDialog.OnItemListener {
            override fun onUse() {
                finish()
            }

        }
        dialog
    }
    private var syncUserCount = 0
    private val qqDialog: ContactUsDialog by lazy {
        ContactUsDialog(this)
    }

    private val privacyColor: Int by lazy {
        ContextCompat.getColor(this, R.color.color_5B3016)
    }

    private var isBuying = false
    private var isJumpLogin = false

    //支付方式 0 微信 1 支付宝
    private var payType = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        immersionBar {
            transparentStatusBar()
            fitsSystemWindows(false)
        }

        initView()
        initData()
        initUser()
        initListener()
    }

    override fun onResume() {
        super.onResume()
        if (isJumpLogin && UserPreference.instance.getUserToken().isNullOrEmpty()) {
            isJumpLogin = false
        }
    }

    private fun initView() {
        val manager = LinearLayoutManager(this, GridLayoutManager.HORIZONTAL, false)
        binding.rvVipTypeList.layoutManager = manager
        binding.rvVipTypeList.adapter = adapter

        // 调用工具类方法设置隐私协议文本
        PrivacyProtocolHelper.setupPrivacyProtocolText(
            textView = binding.tvPrivacyProtocol,
            privacyColor = privacyColor,
            protocolClickListener = {
                WebViewActivity.launch(this, "会员服务协议", Constants.PrivacyUrl.protocol.url)
            },
            privacyClickListener = {
                WebViewActivity.launch(this, "自动续费服务规则", Constants.PrivacyUrl.privacy.url)
            }
        )

//        if (AppUtil.canShowAd()){
//            if (UserPreference.instance.isVip()){
//                binding.tvRewardMember.visibility = View.INVISIBLE
//            }else if (UserPreference.instance.isWatchReward()){
//                binding.tvRewardMember.visibility = View.INVISIBLE
//            }else{
//                binding.tvRewardMember.visibility = View.VISIBLE
//            }
//
//        }else{
//            binding.tvRewardMember.visibility = View.INVISIBLE
//        }


    }

    private fun showOpenVipSuccessDialog() {

        openVipSuccessDialog.show()
    }

    override fun onBackPressed() {

        if (userInfo?.isVip == 1) {
            finish()

        } else {

            if (adapter.list.isEmpty()) {
                finish()
                return
            }
            val data = adapter.list[adapter.foreverPosition]
            specialPriceBuyDialog.setPrice("${data.currentPrice}", "${data.originPrice / 100f}")
            specialPriceBuyDialog.show()

        }
    }

    private fun initListener() {
        binding.ivBack.clickWithTrigger {
            onBackPressed()
        }


//        binding.tvMemberProtocol.clickWithTrigger {
//            WebViewActivity.launch(this, "会员服务协议", Constants.PrivacyUrl.memberProtocol.url)
//        }

        binding.tvBuyVip.clickWithTrigger {
            buyVip(adapter.getCheckedProductId())
        }

        binding.tvBuyVipTop.clickWithTrigger {
            buyVip(adapter.getCheckedProductId())
        }
//        binding.tvRewardMember.clickWithTrigger {
//            if (UserPreference.instance.getUserToken().isNullOrEmpty()) {
//                isJumpLogin = true
//                LoginActivity.launch(this)
//                return@clickWithTrigger
//            }
//            showRewardAd(onReward = {
//                //设置临时会员
//                UserPreference.instance.setWatchReward(true)
//                UserPreference.instance.setTempVip(true)
//                UserPreference.instance.setTempExpirationTime()
//                binding.tvRewardMember.visibility = View.INVISIBLE
//                ToastUtils.show("会员领取成功！")
//                //发送临时会员events
//                sendEvent(RewardTempVipEvents(true))
//
//            })
//        }


        binding.layoutAliPay.clickWithTrigger {
            payType = 1
            binding.ivWxChecked.visibility = View.INVISIBLE
            binding.ivAliChecked.visibility = View.VISIBLE
        }
        binding.layoutWxPay.clickWithTrigger {
            payType = 0
            binding.ivWxChecked.visibility = View.VISIBLE
            binding.ivAliChecked.visibility = View.INVISIBLE
        }

    }

    private fun buyVip(productId: Int, special: Int = 0) {
        if (userInfo == null) {
            isJumpLogin = true
            LoginActivity.launch(this)
            return
        }
        userInfo?.let {
            if (payType == 0) {
                //微信支付
                // viewModel.getWxPayInfo(VipPayParams(packageName, it.userId, productId, special, AppUtil.getChannel()))
            } else {
                //todo
                //支付宝创建订单
                //  viewModel.getVipPayInfo(VipPayParams(packageName, it.userId, productId, special, AppUtil.getChannel()))
                logInUserInfo?.let { it1 ->
                    createPayment(
                        it1.token,
                        OrderBean(adapter.getCheckedProductId())
                    )
                }
            }
//            viewModel.getVipPayInfo(VipPayParams(packageName, it.userId, adapter.getCheckedProductId(), special, AppUtil.getChannel()))

        }
    }

    private fun initUser() {
        logInUserInfo = MMKVUtils.getObject(
            com.hlyj.http.base.tool.lib_hlyj_base.Constants.LoginResultBean,
            LoginResultBean::class.java
        )
        if (logInUserInfo != null) {

            if (logInUserInfo?.phone.isNullOrEmpty()) {
                binding.tvUserName.text = "水印相机用户"
            } else {
                binding.tvUserName.text = logInUserInfo?.phone
            }
            userInfo = MMKVUtils.getObject(
                com.hlyj.http.base.tool.lib_hlyj_base.Constants.UserInfoResultBean,
                UserInfoResultBean::class.java
            )
            if (userInfo?.isVip == 1) {
                binding.tvVipStatus.text = "已开通"

            }

        }
    }

    private fun initData() {
        //会员权益获取
        quanyiadapter = VipQuanYiAdapter()
        binding.recyQuanyi.layoutManager = GridLayoutManager(this, 2)
        binding.recyQuanyi.adapter = quanyiadapter
        quanyiadapter?.submitList(viewModel.getVipQuanYiList)
        //登录
        receiveEvent<LoginEvents> {
            initUser()
        }

//        //微信支付
//        receiveEvent<WXPayEvents> {
//            ToastUtils.show("支付成功,正在同步会员信息")
//            lifecycleScope.launch(Dispatchers.IO) {
//                delay(1000)
//                syncUserCount++
//                viewModel.getUserInfo(UserInfoParams(UserPreference.instance.getUserToken()))
//            }
//
//        }
        //获取商品
        getShopListInfo()

        viewModel.aliPayInfo.observe(this) { result ->

            result.doSuccess { baseResponse ->

                baseResponse.data?.let { order ->
                    lifecycleScope.launch(Dispatchers.IO) {
                        val alipay = PayTask(this@VipCenterActivity)
                        val map = alipay.payV2(order, true)
                        val resultStatus = map["resultStatus"]
                        val memo = map["memo"]
                        if (resultStatus == "9000") {
                            //支付成功
                            lifecycleScope.launch(Dispatchers.Main) {
                                loadingPop.showLoadingAndTxt("订单信息同步中请勿关闭当前界面！")
                            }
                            delay(1000)
                            syncUserCount++
                            viewModel.getUserInfo(UserInfoParams(UserPreference.instance.getUserToken()))


                        } else {
                            isBuying = false
                            ToastUtils.show(memo)
                        }
                    }


                }

            }
        }
//
//        viewModel.wxPayInfo.observe(this){result->
//
//            result.doSuccess {baseResponse ->
//                baseResponse.data?.let {
//                    val payReq = PayReq()
//                    payReq.appId = it.appid
//                    payReq.nonceStr = it.noncestr
//                    payReq.packageValue = it.wxPackageName
//                    payReq.partnerId = it.partnerid
//                    payReq.prepayId = it.prepayid
//                    payReq.sign = it.sign
//                    payReq.timeStamp = it.timestamp
//                    WXWrapper.instance.pay(payReq)
//                }
//
//
//
//            }
//
//        }
//
//
//
//        viewModel.userInfoResult.observe(this) { result ->
//            result.doSuccess { baseResponse ->
//                baseResponse.data?.let {
//                    if (it.vipType != userInfo?.vipType || it.vipTime != userInfo?.vipTime) {
//                        binding.tvRewardMember.visibility = View.INVISIBLE
//                        //支付完成 订单同步完成
//                        loadingPop.dismissLoading()
//                        ToastUtils.show("购买成功")
//
//                        //更新本地缓存
//                        UserPreference.instance.setUserInfo(userAdapter.toJson(it))
//                        //发送event 更新界面和vip相关
//                        sendEvent(BuyVipEvents(true))
//
//                        specialPriceBuyDialog.dismiss()
//                        //关闭界面
//                        finish()
//                    } else {
//                        //重新请求--最多三次请求
//                        if (syncUserCount < 3) {
//                            syncUserCount++
//                            viewModel.getUserInfo(UserInfoParams(UserPreference.instance.getUserToken()))
//                        } else {
//                            loadingPop.dismissLoading()
//                        }
//
//                    }
//                }
//
//            }
//            result.doFailure {
//                //重新请求--最多三次请求
//                if (syncUserCount < 3) {
//                    syncUserCount++
//                    viewModel.getUserInfo(UserInfoParams(UserPreference.instance.getUserToken()))
//                } else {
//                    loadingPop.dismissLoading()
//                }
//
//            }
//
//        }

    }


    //获取商品信息
    private fun getShopListInfo() {
        GlobalApi.getShopInfoList(object : ApiCallback<BaseResult<List<ShopInfoBean?>?>> {

            override fun onSuccess(result: BaseResult<List<ShopInfoBean?>?>) {
                adapter.updateData(result.data)
                binding.tvBuyVip.text = "(¥${adapter.getCheckedPrice()})" + "解锁会员"
            }

            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
            }

            override fun onFinish() {
                // 请求完成，可以做一些清理工作
            }
        })
    }

    //创建订单发起支付
    private fun createPayment(token: String, orderBean: OrderBean) {
        GlobalApi.createPayment(token, orderBean, object : ApiCallback<BaseResult<Void?>?> {


            override fun onSuccess(result: BaseResult<Void?>?) {
                lifecycleScope.launch(Dispatchers.IO) {
                    val alipay = PayTask(this@VipCenterActivity)
                    val map = alipay.payV2("", true)
                    val resultStatus = map["resultStatus"]
                    val memo = map["memo"]
                    if (resultStatus == "9000") {
                        //支付成功
                        lifecycleScope.launch(Dispatchers.Main) {
                            loadingPop.showLoadingAndTxt("订单信息同步中请勿关闭当前界面！")
                        }
                        delay(1000)

                        logInUserInfo?.token?.let { getUserInfo(it) }


                    } else {
                        isBuying = false
                        ToastUtils.show(memo)
                    }
                }
            }

            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
            }

            override fun onFinish() {

            }
        })
    }

    /**
     * 获取用户信息
     */
    private fun getUserInfo(token: String) {
        GlobalApi.getUserInfo(token, object : ApiCallback<BaseResult<UserInfoResultBean?>?> {
            override fun onSuccess(result: BaseResult<UserInfoResultBean?>?) {
                if (result?.data != null && result?.data?.isVip == 1) {
                    MMKVUtils.saveObject(
                        com.hlyj.http.base.tool.lib_hlyj_base.Constants.UserInfoResultBean,
                        result?.data
                    )
                    result?.data?.isVip?.let {
                        BaseAdSpUtils.getInstance().putInt(
                            BaseAdConstants.ISVIP,
                            it
                        )
                    }
                } else {
                    //重新请求--最多三次请求
                    if (syncUserCount < 3) {
                        syncUserCount++
                        logInUserInfo?.let { it?.token?.let { it1 -> getUserInfo(it1) } }
                    } else {
                        loadingPop.dismissLoading()
                    }
                }


            }

            override fun onFailure(errorMessage: String) {
                ToastUtils.show(errorMessage)
                //重新请求--最多三次请求
                if (syncUserCount < 3) {
                    syncUserCount++
                    logInUserInfo?.let { it?.token?.let { it1 -> getUserInfo(it1) } }
                } else {
                    loadingPop.dismissLoading()
                }
            }

            override fun onFinish() {

            }

        })
    }


}